import 'package:dynamic_stock/comm/alert_tool.dart';
import 'package:dynamic_stock/const/const.dart';
import 'package:dynamic_stock/model/company_model.dart';
import 'package:dynamic_stock/model/login_model.dart';
import 'package:dynamic_stock/network/network.dart';
import 'package:dynamic_stock/pages/company_user_page.dart';
import 'package:dynamic_stock/pages/login.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CompanyPage extends StatefulWidget {

  @override
  _CompanyPageState createState() => _CompanyPageState();
}

class _CompanyPageState extends State<CompanyPage> with AutomaticKeepAliveClientMixin {
  
  final greyTextstyle = TextStyle(color: Color(0xffA5A5A5),fontSize: 12);
  RefreshController _refreshController;
  List<CompanyModel> list = [];
  int pageIndex = 1;
  int pageSize = 10;

  @override
  initState(){
    super.initState();
    _refreshController = RefreshController(initialRefresh: true);
  }

  @override
  dispose(){
    _refreshController.dispose();
    super.dispose();
  }

  // 请求数据
  _loadData() async {
    pageIndex = 1;
    UserData user = await UserData.instance();
    NetworkTool().request_company(
      {"platComId":user.platComId, "pageIndex":pageIndex, "pageSize":pageSize}
    ).then((res){
      if(res.errcode == 0) {
        setState(() {
          list = res.data.list;
        });
      } else {
        print(res.message);
      }
    }).catchError((e){

    }).whenComplete((){
      if(_refreshController.isLoading) _refreshController.loadComplete();
      if(_refreshController.isRefresh) _refreshController.refreshCompleted(resetFooterState: true);
    });
  }

  // 加载更多
  _onLoadindMore() async {
    UserData user = await UserData.instance();
    pageIndex += 1;
    NetworkTool().request_company(
      {"platComId":user.platComId, "pageIndex":pageIndex, "pageSize":pageSize}
    ).then((res){
      if(res.errcode == 0) {
        setState(() {
          list.addAll(res.data.list);
        });
        if(_refreshController.isLoading) _refreshController.loadComplete();
        if(res.data.list.length < pageSize) _refreshController.loadNoData();
      } else {
        print(res.message);
      }
    }).catchError((e){
      if(_refreshController.isLoading) _refreshController.loadComplete();
    }).whenComplete((){
      if(_refreshController.isRefresh) _refreshController.refreshCompleted();
    });
  }


  _jumpTo(BuildContext context, String comId){
    pushpage(context, CompanyUserPage(stewardComId: comId));
  }

  Widget _createColumn(String title, String val) {
    return Column(
            children: <Widget>[
              Text(val, style: TextStyle(color: Color(0xff5F5D70), fontSize: 18),),
              SizedBox(height: 11,),
              Text(title,style: greyTextstyle,)
            ],
          );
  }

  Widget _createItem(int index, BuildContext context, CompanyModel model) {
    return GestureDetector(
      onTap: (){
        _jumpTo(context, model.stewardComId);
      },
      child: Container(
            color: Colors.white,
            child: Column(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.fromLTRB(25, 27, 25, 0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(right: 13.5),
                        child: Image.asset('assets/company_icon.png'),
                      ),
                      Expanded(
                        child: Padding(
                          padding: const EdgeInsets.only(right: 13.5),
                          child: Text(
                          model.stewardComName, 
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: AppMainColor.tabbarActiveColor, fontSize: 17, fontWeight: FontWeight.bold)),
                        )
                      ),
                      Row(
                        children: <Widget>[
                          Icon(Icons.person, size: 10, color: Color(0xffA5A5A5),),
                          SizedBox(width: 3,),
                          Text(model.stewardComUserCount.toString(),style: greyTextstyle,)
                        ],
                      )
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(25.0),
                  child: Divider(color: AppMainColor.dividerColor,height: 0.5,),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(25, 0, 25, 23.5),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      _createColumn("发展用户数", model.inviteCount.toString()),
                      _createColumn("服务车主数", model.serveVehOwnerCount.toString()),
                      _createColumn("服务在库车辆", model.serveReadyCount.toString()),
                      _createColumn("服务下架车辆", model.serveDownCount.toString()),
                    ],
                  ),
                ),
                Container(height: 10,color: AppMainColor.normalBackColor,)
              ],
            ),
      ),
    );
  }

  _exitLogin(BuildContext context) async {
    bool res = await AlertTool.showDeleteConfirmDialog(context);
    if(res == true){
      // pushReplacement 即使在保存状态的情况下其他的widget也会被销毁
      Navigator.of(context).pushReplacement(MaterialPageRoute(
        builder: (context) => LoginScreen()
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("车管家公司", style: AppTextStyle.tabbarTitleStyle),
        actions: <Widget>[
          FlatButton(
            child: Text("退出",style: TextStyle(color: Color(0xff35343D), fontSize: 15, fontWeight: FontWeight.w400)),
            onPressed: (){
              _exitLogin(context);
            },
          )
        ],
        elevation: 0.5,
      ),
      body: Container(
        color: AppMainColor.normalBackColor,
        child: SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: WaterDropHeader(),
          footer: CustomFooter(
          builder: (BuildContext context,LoadStatus mode){
              Widget body ;
              if(mode==LoadStatus.idle){
                body =  Text("上拉加载更多");
              }
              else if(mode==LoadStatus.loading){
                body =  CupertinoActivityIndicator();
              }
              else if(mode == LoadStatus.failed){
                body = Text("加载失败请重试!");
              }
              else if(mode == LoadStatus.canLoading){
                  body = Text("松开加载更多");
              }
              else{
                body = Text("已经到底了");
              }
              return Container(
                height: 55.0,
                child: Center(child:body),
              );
            },
          ),
          controller: _refreshController,
          onRefresh: _loadData,
          onLoading: _onLoadindMore,
          child: ListView.builder(
            itemBuilder: (context,index){
              return _createItem(index, context, list[index]);
            },
            itemCount: list.length,
          ),
        )
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}